<?php
$path = dirname(__FILE__);
chdir($path);
require_once("./ad_h.php");
require_once("./auto_load.php");


/*
    错误代码列表 以开头编码分类
    0 系统错误 1 店铺错误 2第三方错误
    3 商品错误 4 分类错误 
*/
function error_code($code = ''){
    $error = array(
        "0001" => "非法请求",
        "0002" => "缺少必要的参数",
        "0003" => "系统错误",
        
        "1001" => "店铺信息不存在",
        "1002" => "创建店铺失败",

        "2001" => "创建店铺错误",
        "2002" => "创建分类错误",
        "2003" => "更新分类错误",
        "2004" => "获取分类信息失败",
        "2005" => "删除分类信息失败",
        "2006" => "店铺开业失败",
        "2007" => "更新店铺公告失败",
        "2008" => "获取店铺ID失败",
        "2009" => "批量获取门店详细信息失败",
        "2010" => "添加商品信息失败",
        "2011" => "商品下线失败",
        "2012" => "商品上线失败",
        "2013" => "删除商品失败",

        "3001" => "商品信息不存在",

        "4001" => "开通分类失败",
        "4002" => "关闭分类失败",
        "4003" => "添加分类失败",
    );

    return $error[$code];
}
/*
    数据库操作类
    params
        table_name 表名
*/
function M($tab_name = "")
{
    return new DBModel($tab_name);
}

/*
    头信息debug
    params
        start_time 开始时间 微秒
        log_index 下标
        log_str 记录的内容
*/
function HLog($start_time = 0, $log_index = 0, $log_str = "")
{
    $runTime = (microtime(true) - $start_time) * 1000;

    header(sprintf("A-Debug-%d:%s %.3fms", $log_index, $log_str, $runTime));
}

function DLOG($log_content='', $log_level='', $log_name='')
{ 
    if(empty($log_level)||empty($log_content))
        return;
    
    if(empty($log_name) && $log_level == 'run')
        $log_name = 'run';

    $log_dir = "/mnt/logs/";
    $log_file = $log_dir.$log_name.".".date('Y-m-d').".log";
    
    //默认每行日志必写的内容，统一在这里处理
    // ZHANGXI 2015/1/7 for regular
    $time = sprintf("%8s.%03d",date('H:i:s'),floor(microtime()*1000));
    //$time = date('H:i:s').".".floor(microtime()*1000);
    $ip = sprintf("%15s",$_SERVER["REMOTE_ADDR"]);

    $id =   "";

    $path_arr = array(
        $_GET['m'],
        $_GET['a']
    );

    $content_prefix = "[ ".$time." ".$ip." ".$id." ".$log_level." ".$path_arr[0]." ".$path_arr[1]." ] ";

    /*$fp = fopen($log_file, 'a+');
    fwrite($fp, $content_prefix.$log_content." [".getmypid()."]\n");
    fclose($fp);*/

    error_log($content_prefix.$log_content." [".getmypid()."]\n", 3, $log_file);

    return true;
}

/*
    返回正确经纬度信息
    params
        params_1 参数1
        params_2 参数2
*/
function getPointLocation($params_1 = '', $params_2 = '')
{
    $res = array();
    if($params_1 > 90){
        $res = array(
            "lng" => $params_1,
            "lat" => $params_2
        );
    }else{
        $res = array(
            "lng" => $params_2,
            "lat" => $params_1
        );
    }

    return $res;
}

/*
    获取redis对象
*/
function redisObj()
{
    global $Redis_Memo;
    $redis = new Redis();
    if ($redis->connect($Redis_Memo['host'], $Redis_Memo['port']) == true) {

        if ($redis->auth($Redis_Memo['user'] . ":" . $Redis_Memo['pass']) == true) {
            return $redis;
        }
    }
    return $false;
}

/*
    通过经纬度获取城市信息
    params
        lng 经度信息 高德坐标系
        lat 维度信息 高德坐标系
*/
function getCityInfoByPoint($lng = 0, $lat = 0)
{
    $point = getPointLocation($lng, $lat);

    $data = array(
        "output" => "json",
        "key" => "a98377ae2e53f6d5ff340d7ed44e7e7a",
        "location" => sprintf("%s,%s", $point['lng'], $point['lat'])
    );

    $url = "http://restapi.amap.com/v3/geocode/regeo?" . http_build_query($data);

    $info = json_decode(httpGet($url), true);
    $info = $info['regeocode']['addressComponent'];
    
    if(empty($info)){
        return false;
    }

    $res = array(
        "province" => $info['province'],
        "city" => is_array($info['city']) ? $info['province'] : $info['city'],
        "district" => $info['district'],

    );

    return $res;
}


function httpGet($url){
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_HEADER, false);
    curl_setopt($ch, CURLOPT_AUTOREFERER, true);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);     //  不进行ssl 认证
    // curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5);
    curl_setopt($ch, CURLOPT_TIMEOUT, 10);
    $result = curl_exec($ch);
    curl_close($ch);
    return $result;
}


/*
    添加第三方分类
    params
        channel_id 第三方id
        store_id 店铺id

        category_id 本地分类id

        other_category_id 第三方分类id
        other_category_name 第三方分类名称
        other_category_rank 第三方分类排序
*/
function addChannelCategoryInfo($channel_id = 0, $store_id = 0, $category_id = 0, $other_category_id = 0, $other_category_name = '', $other_category_rank = 0)
{
    $ChannelCategoryModel = new ChannelCategoryModel();

    $res = $ChannelCategoryModel->addCategoryInfo($channel_id, $store_id, $category_id, $other_category_id, $other_category_name, $other_category_rank);
    return $res;
}

/*
    更新第三方分类信息
    params
        other_category_id 第三方分类id
        other_category_name 第三方分类名称
        other_category_rank 第三方分类排序
*/
function updateChannelCategoryInfo($other_category_id = 0, $other_category_name = '', $other_category_rank = 0)
{
    $ChannelCategoryModel = new ChannelCategoryModel();
    $res = $ChannelCategoryModel->updateCategoryInfo($other_category_id, $other_category_name, $other_category_rank);

    return $res;
}

/*
    获取第三方分类信息
    params
        other_category_id 第三方分类id
*/
function getOtherInfoByOtherCategoryId($other_category_id = '')
{
    $ChannelCategoryModel = new ChannelCategoryModel();
    $res = $ChannelCategoryModel->getOtherInfoByOtherCategoryId($other_category_id);

    return $res;
}

/*
    删除第三方分类信息
    params
        channel_id 第三方id
        store_id 店铺id
        other_category_id 第三方分类id
*/
function delChannelCategoryInfo($channel_id = 0, $store_id = 0, $other_category_id = '')
{
    $ChannelCategoryModel = new ChannelCategoryModel();
    $res = $ChannelCategoryModel->delCategoryInfo($channel_id, $store_id, $other_category_id);

    return $res;
}

/*
    更新第三方店铺状态
    params
        channel_id 第三方渠道id
        store_id 店铺id
        store_status 店铺状态 0-停业 1-营业 2-下线
*/
function updateChannelStoreStatus($channel_id = 0, $store_id = 0, $store_status = 0){
    $ChannelStoreModel = new ChannelStoreModel();

    $data = array();
    $data['store_status'] = $store_status;
    $res = $ChannelStoreModel->updateChannelStoreData($channel_id, $store_id, $data);

    return $res;    
}

/*
    更新第三方店铺信息
    params
        chn_id 渠道id
        store_id 店铺id
        other_shop_name 第三方药店名称
        other_shop_desc 第三方药店广告
        start_time 营业开始时间
        end_time 营业结束时间
        shipping_fee 配送费
        store_status 店铺状态
*/
function updateChannelStoreInfo($chn_id = 0, $store_id = 0, $other_shop_name = '', $other_shop_desc = '', $start_time = '', $end_time = '', $shipping_fee = 0, $store_status = 0){
    $ChannelStoreModel = new ChannelStoreModel();

    $data = array();
    $data['other_shop_name'] = $other_shop_name;
    $data['other_shop_desc'] = $other_shop_desc;
    $data['shipping_start_time'] = $start_time;
    $data['shipping_end_time'] = $end_time;
    $data['shipping_fee'] = $shipping_fee;
    $data['store_status'] = $store_status;
    $res = $ChannelStoreModel->updateChannelStoreInfo($chn_id, $store_id, $data);

    return $res;    
}

/*
    查询第三方店铺信息
    params
        channel_id 第三方渠道id
        store_id 店铺id
*/
function getChannelStoreInfo($channel_id = 0, $store_id = 0){
    $ChannelStoreModel = new ChannelStoreModel();

    $res = $ChannelStoreModel->getChannelStoreInfo($channel_id, $store_id);

    return $res;    
}

/*
    通过渠道ID查本地门店ID和第三方门店ID
    params
        channel_id 第三方渠道id
*/
function getOtherShopIdByChnId($channel_id = 0){
    $ChannelStoreModel = new ChannelStoreModel();

    $res = $ChannelStoreModel->getOtherShopIdByChnId($channel_id);

    return $res;    
}

/*
    更新第三方店铺描述
    params
        channel_id 第三方渠道id
        store_id 店铺id
        other_shop_desc 店铺描述信息
*/
function updateChannelStoreTopic($channel_id = 0, $store_id = 0, $other_shop_desc = ''){
    $ChannelStoreModel = new ChannelStoreModel();

    $data = array();
    $data['other_shop_desc'] = $other_shop_desc;
    $res = $ChannelStoreModel->updateChannelStoreData($channel_id, $store_id, $data);

    return $res;    
}

/*
    获取商品信息
    params
        product_id 商品id
        field 查询字段
*/
function getProductInfoById($product_id = 0, $field = '*')
{
    $ProductModel = new ProductModel();

    return $ProductModel->getProductInfoById($product_id, $field);
}

/*
    添加商品信息
    params
        channel_id 渠道id
        store_id 店铺id
        product_id 商品id
        other_category_id 第三方分类id
        other_product_id 第三方商品id
        product_price 商品销售价格 单位：分
        other_spec_id 商品规格ID
*/
function addChannelProductInfo($channel_id = 0, $store_id = 0, $product_id = 0, $other_category_id = '', $other_product_id = '', $product_price = 0, $product_thumb = array(), $other_spec_id = 0){

    $ChannelProductModel = new ChannelProductModel();

    $Dao = M("kfsy_channel_store.kf_channel_product");

    $Dao->startTrans();

    $addProduct = $ChannelProductModel->addChannelProductInfo($channel_id, $store_id, $product_id, $other_category_id, $other_product_id, $product_price, $other_spec_id);

    if($addProduct == false){
        $Dao->rollback();
        return false;
    }

    $addThumb = $ChannelProductModel->addChannelProductThumb($channel_id, $store_id, $product_id, $product_thumb);

    if($addThumb == false){
        $Dao->rollback();
        return false;
    }

    $Dao->commit();

    return $addProduct;
}

/*
    替换商品信息
    params
        channel_id 渠道id
        store_id 店铺id
        product_id 商品id
        other_category_id 第三方分类id
        other_product_id 第三方商品id
        product_price 商品销售价格 单位：分
        product_stock 商品库存
        product_status 商品状态 1-上架 2-下架
*/
function replaceChannelProductInfo($channel_id = 0, $store_id = 0, $product_id = 0, $other_category_id = '', $other_product_id = '', $product_price = 0, $product_stock = 0, $product_status = 0, $product_thumb = array())
{

    $ChannelProductModel = new ChannelProductModel();

    $Dao = M("kfsy_channel_store.kf_channel_product");

    $Dao->startTrans();

    $updateProduct = $ChannelProductModel->replacChannelProductInfo($channel_id, $store_id, $product_id, $other_category_id, $other_product_id, $product_price, $product_stock, $product_status);

    if($updateProduct == false){
        $Dao->rollback();
        return false;
    }

    $ChannelProductModel->clearChannelProductThumb($channel_id, $store_id, $product_id);

    $addThumb = $ChannelProductModel->addChannelProductThumb($channel_id, $store_id, $product_id, $product_thumb);

    if($addThumb == false){
        $Dao->rollback();
        return false;
    }

    $Dao->commit();

    return $updateProduct;
}

/*
    获取第三方商品信息
    params
        channel_id 渠道id
        store_id 店铺id
        product_id 快方商品id
*/
function getChannelProductInfo($channel_id = 0, $store_id = 0, $product_id = 0)
{
    $ChannelProductModel = new ChannelProductModel();

    return $ChannelProductModel->getChannelProductInfo($channel_id, $store_id, $product_id);
}

/*
    获取第三方商品规格ID
    params
        channel_id 渠道id
        store_id 店铺id
        other_product_id 第三方商品id
*/
function getChannelProductSpecID($channel_id = 0, $store_id = 0, $other_product_id = 0)
{
    $ChannelProductModel = new ChannelProductModel();

    return $ChannelProductModel->getChannelProductSpecID($channel_id, $store_id, $other_product_id);
}

/*
    更新第三方商品信息
    params
        channel_id 渠道id
        store_id 店铺id
        product_id 快方商品id
        data  更新的数据对象
*/
function updateChannelProductInfo($channel_id = 0, $store_id = 0, $product_id = 0, $data = array()){
    $ChannelProductModel = new ChannelProductModel();

    return $ChannelProductModel->updateChannelProductInfo($channel_id, $store_id, $product_id, $data);
}

/*
    更新第三方商品库存
    params
        channel_id 渠道id
        store_id 店铺id
        other_product_id 快方商品id
        data  更新的数据对象
*/
function updateChannelProductStock($channel_id = 0, $store_id = 0, $other_product_id = 0, $data = array()){
    $ChannelProductModel = new ChannelProductModel();

    return $ChannelProductModel->updateChannelProductStock($channel_id, $store_id, $other_product_id, $data);
}

/*
    更新第三方商品价格
    params
        channel_id 渠道id
        store_id 店铺id
        other_product_id 快方商品id
        data  更新的数据对象
*/
function updateChannelProductPrice($channel_id = 0, $store_id = 0, $other_product_id = 0, $data = array()){
    $ChannelProductModel = new ChannelProductModel();

    return $ChannelProductModel->updateChannelProductPrice($channel_id, $store_id, $other_product_id, $data);
}

/*
    更新第三方商品状态
    params
        channel_id 渠道id
        store_id 店铺id
        product_id 快方商品id
        status  更新的状态
*/
function updateChannelProductStatus($channel_id = 0, $store_id = 0, $product_id = 0, $status = 0)
{
    $data = array();
    $data['product_status'] = $status;

    return updateChannelProductInfo($channel_id, $store_id, $product_id, $data);
}

/*
    获取第三方商品库存信息
    params
        channel_id 渠道id
        store_id 店铺id
*/
function getChannelProductStock($channel_id = 0, $store_id = 0){
    $ChannelProductModel = new ChannelProductModel();

    return $ChannelProductModel->getChannelProductStock($channel_id, $store_id);
}

/*
    获取第三方商品价格信息
    params
        channel_id 渠道id
        store_id 店铺id
*/
function getChannelProductPrice($channel_id = 0, $store_id = 0){
    $ChannelProductModel = new ChannelProductModel();

    return $ChannelProductModel->getChannelProductPrice($channel_id, $store_id);
}

/*
    通过条形码查询商品id
    params
        upc 商品条形码
*/
function getProdcutIdByUPC($upc = ''){
    $ProductModel = new ProductModel();

    return $ProductModel->getProdcutIdByUPC($upc);
}

/*
    批量替换第三方店铺分类
    params
        data 替换的数据对象数组
*/
function replaceChannelCategory($data = array()){
    $ChannelCategoryModel = new ChannelCategoryModel();

    return $ChannelCategoryModel->replaceChannelCategory($data);
}

/*
    通过渠道ID和本地药店ID查第三方药店ID
    chn_id 渠道ID
    store_id 本地药店ID
*/
function getOtherShopIdByRedis($chn_id=0, $store_id=0)
{
    $MyRedis = new MyRedis();

    $chnKey = array(
        "1" => "MEITUAN",
        "2" => "BAIDU",
        "3" => "JINGDONGDJ",
        "4" => "ELEME"
    );

    $chnCode = $chnKey[$chn_id];
    if(empty($chnCode))
    {
        return false;
    }

    $tmpKey = "KCS_STORE_%s_GET_OTHER_STORE_ID_%s";

    $redisKey = sprintf($tmpKey, $chnCode, $store_id);

    if(empty($MyRedis->GET($redisKey)))
    {
        $channel_store_info = getOtherShopIdByChnId($chn_id);

        if(empty($channel_store_info))
        {
            return false;
        }

        foreach ($channel_store_info as $key => $value) {
            $newRedisKey = sprintf($tmpKey, $chnCode, $value['fk_store_id']);

            $res = $MyRedis->SET($newRedisKey, $value['other_shop_id']);
        }
    }

    $other_shop_id =  $MyRedis->GET($redisKey);

    return $other_shop_id;
}

?>